package com.heqiang.spring.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import com.heqiang.spring.beans.BeansException;
import com.heqiang.spring.beans.factory.DisposableBean;
import com.heqiang.spring.beans.factory.config.BeanDefinition;

import java.lang.reflect.Method;

public class DisposableBeanAdppter implements DisposableBean {

    private final Object bean;

    private final String beanName;

    private String destroyMethodName;


    public  DisposableBeanAdppter (String beanName, Object bean, BeanDefinition beanDefinition) {
        this.beanName = beanName;
        this.bean  = bean;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {
        //实现DisposableBean接口
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }
        //注解配置 destroy-method {判断是为了避免二次执行销毁}
        if (StrUtil.isNotEmpty(destroyMethodName) && !(bean instanceof DisposableBean && "destroy".equals(this.destroyMethodName))) {
            Method method =bean.getClass().getMethod(destroyMethodName);
            if (null == method) {
                throw new BeansException("不能找到销毁方法"+destroyMethodName);
            }
            method.invoke(bean);
        }
    }
}
